//
//  BCSvipBuyController.m
//  GSBlockChain
//
//  Created by guoshikeji_a on 2018/12/20.
//  Copyright © 2018 guoshikeji. All rights reserved.
//

#import "BCSvipBuyController.h"

#import "BCProtocolController.h"

#import "BCUserSafeCenterRequest.h"
#import "BCWalletPassSetController.h"

#import "BCSvipPayPassController.h"

static NSString *svipBuyProtoclLinkString = @"protocol://";

@interface BCSvipBuyController () <QMUITextViewDelegate,BCWalletPassSetControllerDelegate>

@property (nonatomic, strong) QMUILabel *titleLabel;

/**
 *amountTF
 */
@property (nonatomic, strong) QMUITextField *amountTF;

/**
 *payBalanceLabel
 */
@property (nonatomic, strong) QMUILabel *payBalanceLabel;

/**
 *doneButton
 */
@property (nonatomic, strong) QMUIButton *doneButton;

/**
 *protocolTV
 */
@property (nonatomic, strong) QMUITextView *protocolTV;


/**
 *contentView动态计算后的高度
 */
@property (nonatomic, assign) CGFloat contentHeight;

#pragma mark - data

@property (nonatomic, strong) BCUserSvipData *svipData;

/**
 *BCSvipBuyControllerCompleteBlock
 */
@property (nonatomic, copy) BCSvipBuyControllerCompleteBlock completeBlock;

@end

@implementation BCSvipBuyController

+ (void)showBuyFromController:(UIViewController *)fromController data:(BCUserSvipData *)svipData complete:(BCSvipBuyControllerCompleteBlock)complete {
    BControllerWindow *window = [[BControllerWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    BCSvipBuyController *vc = [BCSvipBuyController new];
    vc.showWindow = window;
    vc.svipData = svipData;
    vc.completeBlock = complete;
    BCWindowNavigationController *nav = [[BCWindowNavigationController alloc] initWithRootViewController:vc];
    nav.navigationBar.hidden = true;
    nav.navigationBar.barStyle = UIBarStyleDefault;
    window.rootViewController = nav;
    [window makeKeyAndVisible];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //
    [self setupSubviews];
    //
    [self showContentView];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

//
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    UITouch *touch = touches.anyObject;
    CGPoint touchPoint = [touch locationInView:self.view];
    if (!CGRectContainsPoint(self.contentView.frame, touchPoint)) {
        [self dismissContentView];
    }
}

- (void)setupSubviews {
    [self.view addSubview:self.backgroundView];
    [self.backgroundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    [self.view addSubview:self.contentView];
    [self.contentView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(self.view);
        make.bottom.mas_equalTo(self.view);
    }];
    self.contentView.layer.shadowOpacity = 1;
    self.contentView.layer.shadowRadius = 10.0;
    self.contentView.layer.shadowColor = [UIColor qmui_colorWithHexString:@"#33000000"].CGColor;
    self.contentView.layer.shadowOffset = CGSizeMake(0, -2);
    //
    [self setupContents];
    [self.view layoutIfNeeded];
}
- (void)setupContents {
    //各种间隔的总和
    CGFloat totlePaddingHeight = 0;
    CGFloat leftPadding = 20.0;
    //项目名称
    CGFloat topPadding = 18.0;
    self.titleLabel = [QMUILabel new];
    self.titleLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.titleLabel.numberOfLines = 0;
    self.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    [self.contentView addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.contentView).offset(topPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
    }];
    self.titleLabel.text = self.svipData.flow.buy_title;
    [self.titleLabel sizeToFit];
    totlePaddingHeight += topPadding;
    //tf
    self.amountTF = [QMUITextField new];
    self.amountTF.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.amountTF.tintColor = self.amountTF.textColor;
    self.amountTF.font = [UIFont systemFontOfSize:16 weight:UIFontWeightMedium];
    self.amountTF.placeholderColor = [UIColor qmui_colorWithHexString:@"#FFD6D6D6"];
    [self.contentView addSubview:self.amountTF];
    [self.amountTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.titleLabel.mas_bottom).offset(topPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
        make.height.mas_equalTo(50.0);
    }];
    self.amountTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 10);
    self.amountTF.layer.borderColor = [UIColor qmui_colorWithHexString:@"#FFC2C2C2"].CGColor;
    self.amountTF.layer.cornerRadius = 2;
    self.amountTF.layer.borderWidth = 2;
    self.amountTF.enabled = false;
    //
    self.amountTF.text = [NSString stringWithFormat:@"%@%@",self.svipData.buy.amount,self.svipData.buy.cur_sign];
    totlePaddingHeight += topPadding;
    //pay_balance
    CGFloat payBlancePadding = 40.0;
    self.payBalanceLabel = [QMUILabel new];
    self.payBalanceLabel.textColor = [UIColor qmui_colorWithHexString:@"#FF666666"];
    self.payBalanceLabel.font = [UIFont systemFontOfSize:16 weight:UIFontWeightRegular];
    [self.contentView addSubview:self.payBalanceLabel];
    [self.payBalanceLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.amountTF.mas_bottom).offset(payBlancePadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
    }];
    self.payBalanceLabel.text = [NSString stringWithFormat:@"%@%@%@",self.svipData.flow.balance,self.svipData.buy.balance,self.svipData.buy.cur_sign];
    totlePaddingHeight += payBlancePadding;
    //doneButton
    CGFloat doneButtonPadding = 15.0;
    self.doneButton = [QMUIButton new];
    [self.doneButton setTitle:self.svipData.flow.not_buy forState:UIControlStateNormal];
    [self.doneButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    self.doneButton.titleLabel.font = [UIFont systemFontOfSize:18 weight:UIFontWeightMedium];
    self.doneButton.backgroundColor = [UIColor darkMainColor];
    self.doneButton.layer.cornerRadius = 2;
    [self.contentView addSubview:self.doneButton];
    [self.doneButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.payBalanceLabel.mas_bottom).offset(doneButtonPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
        make.height.mas_equalTo(50.0);
    }];
    [self.doneButton addTarget:self action:@selector(doneButtonDidClickedAction) forControlEvents:UIControlEventTouchUpInside];
    totlePaddingHeight += doneButtonPadding;
    //当余额不足时需要处理吗
    if (self.svipData.buy.balance.floatValue<self.svipData.buy.amount.floatValue) {
        self.doneButton.userInteractionEnabled = false;
        self.doneButton.backgroundColor = [UIColor qmui_colorWithHexString:@"#C1C0C9"];
    }
    
    //比较麻烦的底部tv
    CGFloat protocolTVPadding = 11.0;
    self.protocolTV = [QMUITextView new];
    self.protocolTV.textAlignment = NSTextAlignmentCenter;
    self.protocolTV.scrollEnabled = false;
    self.protocolTV.editable = false;
    self.protocolTV.delegate = self;
    self.protocolTV.textContainerInset = UIEdgeInsetsMake(0, 0, 0, 0);
    [self.contentView addSubview:self.protocolTV];
    [self.protocolTV mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.doneButton.mas_bottom).offset(protocolTVPadding);
        make.left.mas_equalTo(self.contentView).offset(leftPadding);
        make.right.mas_equalTo(self.contentView).offset(-leftPadding);
        //        make.height.mas_equalTo(40.0);
    }];
    self.protocolTV.linkTextAttributes = @{ NSForegroundColorAttributeName: [UIColor qmui_colorWithHexString:@"#FFAEAEAE"],
                                            NSUnderlineColorAttributeName: [UIColor qmui_colorWithHexString:@"#FFAEAEAE"],
                                            NSUnderlineStyleAttributeName: @(NSUnderlineStyleSingle)};
    
    NSMutableParagraphStyle *protocolPs = [[NSMutableParagraphStyle alloc] init];
    protocolPs.alignment = NSTextAlignmentCenter;
    NSString *protocolString = [NSString stringWithFormat:@"%@%@",self.svipData.flow.button_text,self.svipData.flow.agreement_text];
    NSMutableAttributedString *protocolAttri = [[NSMutableAttributedString alloc] initWithString:protocolString attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:13 weight:UIFontWeightRegular],NSForegroundColorAttributeName:[UIColor qmui_colorWithHexString:@"#FFAEAEAE"],NSParagraphStyleAttributeName:protocolPs}];
    
    NSRange linkRange = [protocolString rangeOfString:self.svipData.flow.agreement_text];
    if (linkRange.location!=NSNotFound) {
        [protocolAttri addAttribute:NSLinkAttributeName value:svipBuyProtoclLinkString range:linkRange];
    }
    self.protocolTV.attributedText = protocolAttri;
    totlePaddingHeight += protocolTVPadding;
    [self.protocolTV sizeToFit];
    
    //
    CGFloat bottomPadding = 15.0;
    totlePaddingHeight += bottomPadding;
    [self.contentView layoutIfNeeded];
    //
    CGFloat contentHeight = totlePaddingHeight;
    contentHeight += CGRectGetHeight(self.titleLabel.frame);
    contentHeight += CGRectGetHeight(self.amountTF.frame);
    contentHeight += CGRectGetHeight(self.payBalanceLabel.frame);
    contentHeight += CGRectGetHeight(self.doneButton.frame);
    contentHeight += CGRectGetHeight(self.protocolTV.frame);
    //
    self.contentHeight = contentHeight+Height_Bottom_SafeArea;
    //
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(self.contentHeight);
        make.bottom.mas_equalTo(self.view).offset(self.contentHeight);
    }];
}

#pragma mark - UITextViewDelegate

- (BOOL)textView:(UITextView *)textView shouldInteractWithURL:(NSURL *)URL inRange:(NSRange)characterRange {
    if ([URL.absoluteString isEqualToString:svipBuyProtoclLinkString]) {
        [BCProtocolController showFromController:self.navigationController protocolURLString:self.svipData.flow.agreement];
        return false;
    }
    return YES;
}

#pragma mark - action
- (void)showContentView {
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(0);
    }];
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        
    }];
}
- (void)dismissContentView {
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(self.view).offset(self.contentHeight);
    }];
    [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionCurveEaseOut animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [self dismissWindow];
    }];
}

#pragma mark - doneButtonDidClickedAction
- (void)doneButtonDidClickedAction {
    [self checkUserSetPayPass];
}
//
#pragma mark -
/**
 检查是否设置了支付密码
 */
- (void)checkUserSetPayPass {
    BCUserSafeCenterData *safeData = [BCUserManager sharedUser].safeCenterData;
    if (safeData) {
        //去支付
        [self toPayAction:safeData];
    }else {
        [self requestPayPassSetAction];
    }
}
#pragma mark - other request
- (void)requestPayPassSetAction {
    //请求一次是否设置了支付密码
    WEAK_SELF
    [self.doneButton bc_showActivityIndicatorBackgroundColor:self.doneButton.backgroundColor insets:UIEdgeInsetsZero activityIndicatorViewStyle:UIActivityIndicatorViewStyleWhite];
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        [wself.doneButton bc_hiddenActivityIndicator];
        if (error) {
            if (wself.view) {
                NSString *errMsg = error.domain;
                [QMUITips showError:errMsg inView:wself.view hideAfterDelay:[QMUITips smartDelaySecondsForTipsText:errMsg]];
            }
        }else {
            //去支付
            [wself toPayAction:resp.data];
        }
    }];
}


#pragma mark - toPayAction
- (void)toPayAction:(BCUserSafeCenterData *)safeData {
    //判断是否开启支付密码
    if (safeData.data.has_pay_pass) {
        //弹出支付界面
        [self toInputPayPassAction];
    }else {
        WEAK_SELF
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:safeData.flow.no_paypass.mess message:nil preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.cancel style:UIAlertActionStyleCancel handler:nil];
        UIAlertAction *setting = [UIAlertAction actionWithTitle:safeData.flow.no_paypass.sub style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [wself toSetPayPassAction];
        }];
        [alertVC addAction:cancel];
        [alertVC addAction:setting];
        [self presentViewController:alertVC animated:true completion:nil];
    }
}
/**
 去设置支付密码
 */
- (void)toSetPayPassAction {
    //需要处理数据
    BCUserSafeCenterData *data = [BCUserManager sharedUser].safeCenterData;
    NSString *account;
    BCaptchaSendType sendType = BCaptchaSendTypePhone;
    if (data.data.has_email) {
        account = data.data.email;
        sendType = BCaptchaSendTypeEmail;
    }else if (data.data.has_phone) {
        account = data.data.phone;
        sendType = BCaptchaSendTypePhone;
    }
    if (!account.length) {
        return;
    }
    BCWalletPassSetController *pass = [BCWalletPassSetController new];
    pass.account = account;
    pass.sendType = sendType;
    pass.delegate = self;
    [self.navigationController pushViewController:pass animated:true];
}
#pragma mark - BCWalletPassSetControllerDelegate
- (void)walletPassSetSuccessAction {
    [BCUserSafeCenterRequest requestData:^(BCUserSafeCenterResponse * _Nonnull resp, NSError * _Nonnull error) {
        
    }];
}
//
/**
 弹出支付密码输入界面 并完成支付
 */
- (void)toInputPayPassAction {
    WEAK_SELF
    [BCSvipPayPassController showPayFromController:self.navigationController complete:^(NSString * _Nonnull successMsg) {
        if (wself.completeBlock) {
            wself.completeBlock(successMsg);
        }
        [wself dismissContentView];
    }];
}


@end
